var express = require('express');
var request = require('request');
var router = express.Router();
var userTest = require('../../db.json');
const DOMAIN = process.env.DOMAIN_NOW;
const SSO_BASE_URL = 'http://sso.com'


router.get('/', function(req, res) {
    res.render('index',{domain:DOMAIN});
});

router.get('/get-user-info',function(req, res) {
    var ticket = req.query.ticket;
    var url = SSO_BASE_URL + '/get-uid';
    var options = {
        qs:{ticket:ticket},
        json:true,
        timeout:5000
    };
    request.get(url,options,function(error,response/*,body*/) {
        if (error || !response || response.statusCode != 200) {
            console.error('获取用户信息时失败',error,response?response.statusCode:0);
            return res.send({code:1,msg:'获取用户信息时失败'});
        }
        // if (body.uid !== userTest.id) {//这句话其实不会运行到，因为我们仅仅配置了一个用户
        //     return res.send({code:2,msg:'当前用户数据非法'});
        // }
        req.session.user = userTest;
        res.send({code:0});
    });
    // res.send({uid:uid});
});

router.get('/user-backend',function(req, res) {
    var user = req.session.user || {};
    res.render('user',{username:user.account});
});

// router.post('/login',function(req, res) {
//     var _body = req.body;
//     var username = _body.username;
//     var password = _body.password;

//     if (username !== userTest.account || password !== userTest.password) {
//         return res.send({code:1,msg:'用户名或者密码错误'});
//     }
//     crypto.randomBytes(16,function(err,bytes) {
//         if (err) {
//             console.error('生成随机数失败',err);
//             return res.send({code:2,msg:'生成凭证失败'});
//         }
//         var ticket = bytes.toString('hex');
//         res.set('P3P','CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');

//         res.cookie('ticket',ticket);
//         ticketData[ticket] = userTest.uid;

//         res.send({code:0});
//     });
    
// });

module.exports = router;
